
package com.yimi.service;

import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import com.yimi.common.Message;
import com.yimi.common.MessageType;
import com.yimi.taskmanager.DownloadImageTask;
import com.yimi.taskmanager.QueryImageListTask;
import com.yimi.taskmanager.QueryPreviewTask;
import com.yimi.taskmanager.TaskListener;
import com.yimi.taskmanager.ThreadPool;

import java.net.URLConnection;
import java.util.List;

/**
 * SearchService.java Create on 2012-7-30     
 *      
 * Copyright (c) 2012-7-30 by yiming     
 *      
 * @author <a href="alenzhangym@hotmail.com">Yiming</a>     
 * @version 1.0 
 */

/**
 * @author Yiming
 * @version 1.0
 */
public class SearchService extends MessageService implements TaskListener {
    public final String QUERY_IMAGE_LIST_SERVER = "http://chan.sankakucomplex.com/post/index.json";
    public static final int PAGESIZE = 10;
    public static final int MAX_BITMAP_SIZE = 5237760;
    public static final int MAX_SEND_SIZE = MAX_BITMAP_SIZE / 5;
    private String queryName;
    private RemoteCallbackList<ISearchServiceCallBack> statusListeners;
    
    private DownloadImageTask downloadImageTask;
    private ISearchService.Stub binder = new com.yimi.service.ISearchService.Stub() {
        @Override
        public void queryImagesEntity(final String page, final String queryTarget)
                throws RemoteException {
            if (!queryName.equals(queryTarget)) {
                queryName = new String(queryTarget);
            }
            final Integer queryPage = Integer.decode(page);
            // final String taskCommand = "QUERYIMAGELIST" + page + queryTarget;
            String url = QUERY_IMAGE_LIST_SERVER + "?tags=" + queryName + "&limit="
                    + PAGESIZE + "&page=" + page;
            QueryImageListTask task = new QueryImageListTask(queryPage, queryTarget, url);
            task.registerTaskListener(SearchService.this);
            ThreadPool.getInstance().addTask(task);
        }
        
        @Override
        public void queryPreview(Entity baseItem){
            QueryPreviewTask queryPreviewTask = new QueryPreviewTask((BaseImageItem) baseItem);
            queryPreviewTask.registerTaskListener(SearchService.this);
            ThreadPool.getInstance().addTask(queryPreviewTask);
        }
        
        @Override
        public void registerListeners(ISearchServiceCallBack callback)
                throws RemoteException {
            statusListeners.register(callback);
        }

        @Override
        public void queryImagePreviews(final int page, final Entity imageList)
                throws RemoteException {
            ImageList list = (ImageList) imageList;
            List<BaseImageItem> querylist = list.getImageList();
            for (int i = 0; i < querylist.size(); i++) {
                BaseImageItem item = querylist.get(i);
                QueryPreviewTask queryPreviewTask = new QueryPreviewTask(item);
                queryPreviewTask.registerTaskListener(SearchService.this);
                ThreadPool.getInstance().addTask(queryPreviewTask);
            }
        }
        
        public void cacelQueryListTask(String targetName){
            
        }
        
        public void cancelDownloadImage(String fileURL) {
            if (downloadImageTask != null) {
                if (downloadImageTask.getTaskCommand().equals(fileURL)) {
                    downloadImageTask.unRegisterDownloadImageListener(SearchService.this);
                    downloadImageTask.stop();
                }
            }
        }

        @Override
        public void queryImageFileView(final String fileURL) throws RemoteException {
            if (downloadImageTask != null) {
                downloadImageTask.unRegisterDownloadImageListener(SearchService.this);
                downloadImageTask.stop();
            }
            downloadImageTask = new DownloadImageTask(fileURL);
            downloadImageTask.registerTaskListener(SearchService.this);
            ThreadPool.getInstance().addTask(downloadImageTask);
        }
    };

    public static void printHeader(URLConnection conn) {
        int i = 1;
        while (true) {
            String header = conn.getHeaderFieldKey(i);
            i++;
            if (header != null) {
                Log.i("Search service", header + ":" + conn.getHeaderField(i));
            } else {
                break;
            }
        }
    }

    protected void addQueryMapFailedMessage(int type, String fileURL) {
        Message message = new Message(MessageType.EVENT_QUERYFILEVIEWFAILED);
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setFileURL(fileURL);
//        imageEntity.setImage(new byte[0]);
        message.setResult(imageEntity);
        message.setType(MessageType.TYPE_QUEYRMAP_FAILED);
        addMessage(message);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        Log.e(this.getClass().getName(), "get bind");
        return binder;
    }

    public void onCreate() {
        super.onCreate();
        Log.e(this.getClass().getName(), "Start create");
        statusListeners = new RemoteCallbackList<ISearchServiceCallBack>();
        queryName = "";
        Log.e(this.getClass().getName(), "create over");
    }

    public void onDestroy() {
        super.onDestroy();
        ThreadPool.getInstance().destroy();
    }

    /*
     * (non-Javadoc)
     * @see com.yimi.service.MessageService#sendNotify(com.yimi.common.Message)
     */
    @Override
    public synchronized void sendNotify(Message message) {
        int size = statusListeners.beginBroadcast();
        for (int i = 0; i < size; i++) {
            ISearchServiceCallBack callback = statusListeners.getBroadcastItem(i);
            try {
                Log.e("callback ", "onevent");
                callback.onEvent(message.getEvent(), message.getType(), message.getResult());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        statusListeners.finishBroadcast();
    }
}
